package com.atguigu.jdbc3;

import com.atguigu.jdbc.JDBCUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author 798133716@qq.com
 * @create 2021-02-27 8:25
 */
public class ThansactionDemo {

    @Test
    public void test(){
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement ps = null;
        try {
            connection.setAutoCommit(false);
            String sql = "update demo1 set username=? where id = ?";
            ps = connection.prepareStatement(sql);
            ps.setString(1,"haha");
            ps.setInt(2,2);
            ps.executeUpdate();
           // System.out.println(1/0);
            ps.setString(1,"woyehaha");
            ps.setInt(2,3);
            ps.executeUpdate();
            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {
            try {
                connection.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JDBCUtils.close(ps,connection);
        }
    }
}
